package com.ceiec.scm.feigncontroller;

import com.ceiec.scm.vo.TestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;

@RestController
public class TestController implements CommandLineRunner {


    @Resource
    @Qualifier("redisScript")
    private DefaultRedisScript<Boolean> redisScript;

    @Resource
    @Qualifier("modifyJsonRedisScript")
    private DefaultRedisScript<Object> modifyJsonRedisScript;


    @Autowired
    @Qualifier("defaultRedisTemplate")
    private RedisTemplate<String,Object> redisTemplate;


    @Autowired
    @Qualifier("customRedisTemplate")
    private RedisTemplate<String,Object> customRedisTemplate;

    @GetMapping("/lua")
    public ResponseEntity lua() {
        List<String> keys = Arrays.asList("testLua", "hello lua");
        Boolean execute = redisTemplate.execute(redisScript, keys, 100);
        assert execute != null;
        return ResponseEntity.ok(execute);
    }

    @GetMapping("/modifyJsonLua")
    public ResponseEntity modifyJsonLua() throws UnsupportedEncodingException {
        byte[] bytes1 = "ckl".getBytes("utf-8");
        System.out.println(bytes1);
        List<String> keys = Arrays.asList("HASH_TEST");
        byte[] bytes = new byte[3];
        bytes[0] = 'c';
        bytes[1] = 'k';
        bytes[2] = 'l';

        byte[] bytesOfVoProperty = new byte[5];
        bytesOfVoProperty[0] = 'c';
        bytesOfVoProperty[1] = 'o';
        bytesOfVoProperty[2] = 'u';
        bytesOfVoProperty[3] = 'n';
        bytesOfVoProperty[4] = 't';



        Object execute = customRedisTemplate.execute(modifyJsonRedisScript, keys, "ckl".getBytes("utf-8"), "count".getBytes("utf-8"));
        System.out.println(execute);
        return ResponseEntity.ok(execute);
    }


    @Override
    public void run(String... args) throws Exception {
        HashOperations<String, Object, Object> ops =
                redisTemplate.opsForHash();
        TestVO vo = new TestVO();
        vo.setCount(123);
        ops.put("HASH_TEST","ckl", vo);
    }
}
